import createIDB from '../idb'
import IndexDBModel from './model'

/**
 * IndexDB数据存储服务对象
 * hainee@163.com 2020-11
 * @param {*} dbName 数据库名称
 */
export default function InedxDBStore({ dbName, config }) {
  this.db = null
  this.config = null
  this.models = {}
  this.initialized = false

  /**
   * 初始化存储服务对象
   */
  this.init = async function () {
    if (this.initialized) {
      return this
    }
    this.dbName = dbName
    this.config = config
    this.db = await createIDB(this.config)
    // 根据配置初始化实体对象
    this.config.tables.forEach((tableCfg) => {
      const Model = tableCfg.model
      this.models[tableCfg.tableName] = new IndexDBModel(this, tableCfg)
    })
    this.initialized = true
    return this
  }
}
